// 修改 ECSSys.ts
import { ECSEntity } from "./ECSEntity";
import { ECSWorld } from "./ECSWorld";
import { IEntityFilter } from "./EntityFilter";
import { ECSBase } from "./ECSBase";

export abstract class ECSSys extends ECSBase {
    /**
     * 系统id
     */
    public readonly id: number;
    /**
     * 系统优先级
     */
    public readonly priority: number;
    /**
     * 系统过滤器
     */
    private _filter: IEntityFilter;
    /**
     * 实体
     */
    private _entities: number[] = [];
    get entities(): number[] {
        return this._entities;
    }
    /** 
     * 获取所属世界 
     */
    private _world: ECSWorld | null = null;
    get world(): ECSWorld | null { return this._world; }


    /** 启用状态 */
    private _enabled: boolean = true;
    get enabled(): boolean { return this._enabled; }
    set enabled(value: boolean) {
        if (this._enabled === value) return;
        this._enabled = value;
        this._enabled ? this.onEnable?.() : this.onDisable?.();
    }

    constructor(world: ECSWorld, id: number, priority: number, filter?: IEntityFilter) {
        super();
        this._world = world
        this.id = id;
        this.priority = priority;
        this._filter = filter
    }


    /** 
     * 检查实体是否匹配
     */
    match(entity: ECSEntity): boolean {
        // 没有过滤条件全部通过
        if(this._filter == null) return true;
        return this._filter.match(entity);
    }

    /** 
     * 添加实体
     */
    addEntity(id: number): void {
        if (this.hasEntity(id)) return
        const entity = this.world.getEntity(id)
        if (this.match(entity)) {
            this._entities.push(id)
        }
    }

    /** 
     * 是否有实体 
     */
    hasEntity(id: number): boolean {
        return this._entities.indexOf(id) >= 0;
    }

    /** 
     * 移除实体 
     */
    removeEntity(id: number): void {
        const index = this._entities.indexOf(id);
        if (index >= 0) {
            this._entities.splice(index, 1);
        }
    }

    /**
     * 移除所有实体
     */
    removeAllEntity(): void {
        this._entities.length = 0;
    }


    /**************************内部使用*********************** */
    _ecsEnable(): void {
        this.onEnable()
    }

    _ecsDisable(): void {
        this.onDisable()
    }

    _ecsUpdate(dt: number): void {
        if (!this._enabled) return;
        this.onUpdate(dt);
    }

    _ecsDestroy(): void {
        this.onDestroy();
        this._entities.length = 0
        this._filter = null
        this._world = null;
    }
    /**************************内部使用*********************** */
}